#!/usr/bin/env python

""" sicu.py Swarm Image Conversion Utility
    Converts data in the file whose name is stored in the variable fileName
    to a fileFormat image  using the colors stored in the color variable
    of size width, height and writes the images to the renderDir folder."""

import sys
try:
    import Image, ImageDraw
except ImportError:
    print "Import Error: requires Python Imaging Library."
    sys.exit(0)

width   = 700
height  = 700
bgColor = None
fileFormat = "JPEG"
renderDir  = 'images'
fileName   = 'dump'
animName   = 'swarm'
verbose    = True

# should be no more than 4 colors
color = [(18, 39, 69), (41, 89, 155), (62, 136, 240), ( 41, 56, 11), (102, 140, 27), (167, 227, 44), (54, 11, 2), (138, 28, 6), (224, 44, 10)]
# color = ['red', 'blue', 'grey', 'white', 'yellow', 'green', 'black', 'purple', 'orange' ]

def createImage(matrix,frameNumber):
    """createImage: creates draws and saves image representing swarm data."""
    if verbose:
        print "frame %d" % frameNumber
    image = Image.new("RGB", (width, height), bgColor)
    drawFrame(matrix, image)
    writeFrame(image, frameNumber)

def drawFrame(matrix, image ):
    """ drawFrame loops thru swarm matrix data and draws appropriately colored
        rectangles in image variable."""
    # initialize some variables
    x_inc = float(width)/len(matrix[0])
    y_inc = float(height)/len(matrix)
    drawImage = ImageDraw.Draw(image)

    # Loop Thru matrix drawing rectangles in matrix value color
    for row in range(len(matrix)):
        for col in range(len(matrix[0])):
            curColor = color[matrix[col][row]]
            x1 = x_inc*col
            y1 = y_inc*row
            x2 = x1 + x_inc
            y2 = y1 + y_inc
            drawImage.rectangle((x1, y1, x2, y2), fill=curColor)

def writeFrame(image, frameNumber):
    """ writeFrame: saves image in images directory with name given by animName
        appended by zero padded frameNumber. """
    # format number with zero padding: 00001, 00002, etc
    fileNumber = str(frameNumber).zfill(5)
    imageName = '%s/%s_%s.%s' % (renderDir, animName, fileNumber, fileFormat.lower())
    image.save(imageName, fileFormat)
    
def processDump(fileHandle):
    """ processDump: reads and processes each line in swarm data, assumes but
        doesn't test for properly formatted data and that map iterations are
        separated by blank lines containing only a new line character."""
    count = 0
    mapMatrix = []
    mapRow    = []
    for line in fileHandle:
        if line != '\n':
            for val in line[:-1].split(' '):
                if val != '':
                    mapRow.append(int(val))
            mapMatrix.append(mapRow)
            mapRow = []
        else:
            try:
                createImage(mapMatrix, count)
            except IOError, msg:
                #   image folder doesn't exist
                sys.stderr.write("IO Error: " + str(msg) +"\n")
                break
            mapMatrix = []
            mapRow = []
            count += 1

def main():
    """ Main entry point of Swarm Image Conversion Utility. Attempts to open
        and process swarm data file."""
    try:
        fileHandle = open(fileName, 'r')
        try:
            processDump(fileHandle)
        finally:
            fileHandle.close()
    except IOError, msg:
        sys.stderr.write("IO Error: " + str(msg) +"\n")

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        sys.stderr.write("User Interrupt\n")
